/*
 * Dijjer - A Peer to Peer HTTP Cache
 * Copyright (C) 2004,2005 Change.Tv, Inc
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */
package dijjer.io.xfer;

import java.io.IOException;
import java.io.OutputStream;
import dijjer.io.comm.RetrievalException;

public class OutputStreamBlockTransmitter {

	PartiallyReceivedBlock _prb;
	OutputStream _os;

	public OutputStreamBlockTransmitter(PartiallyReceivedBlock prb, OutputStream os) {
		_prb = prb;
		_os = os;
	}

	public void start() throws RetrievalException, IOException {
		final Thread myThread = Thread.currentThread();
		int currentPacket = 0;
		_prb.addListener(new PartiallyReceivedBlock.PacketReceivedListener() {

			public void packetReceived(int packetNo) {
				synchronized (myThread) {
					myThread.notify();
				}
			}

			public void receiveAborted(int reason, String description) {
				synchronized (myThread) {
					myThread.notify();
				}
			}
		});
		while (currentPacket < _prb.getNumPackets()) {
			while ((!_prb.isReceived(currentPacket)) && (!_prb.isAborted())) {
				synchronized (myThread) {
					try {
						myThread.wait();
					} catch (InterruptedException e) {
					}
				}
			}
			if (_prb.isAborted()) {
				throw new RetrievalException(_prb.getAbortReason(), _prb.getAbortDescription());
			}
			_os.write(_prb.getPacket(currentPacket).getData());
			currentPacket++;
		}
	}
}
